
package com.rt.schedulenew.core.support.shiro;

import java.util.Map;
import java.io.PrintWriter;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;

import com.rt.schedulenew.utils.jwt.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import com.rt.schedulenew.utils.util.EhCacheUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletRequest;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

public class CORSAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (request instanceof HttpServletRequest) {
            String token = ((HttpServletRequest) request).getHeader("token");
            if ("scheduleadmin".equals(token)) {
                return true;
            }
            String EhCheValue = (String) EhCacheUtil.get(ConstantsUtil.EhCacheName.tokenCache.name(), token);
            HttpServletRequest servletRequest = ((HttpServletRequest) request);
            String terminalType = servletRequest.getHeader("TerminalType");
            if ("OPTIONS".equals(servletRequest.getMethod().toUpperCase())) {
                return true;
            }
            if ("B".equals(terminalType)) {
                return true;
            }
            if ("H".equals(terminalType)) {
                return true;
            }
            if ("C".equals(terminalType)  && StringUtils.isNotBlank(token) && token.equals(EhCheValue)) {
                return true;
            }
            if ("D".equals(terminalType)
                    && StringUtils.isNotBlank(token) && token.equals(EhCheValue)) {
                // 验证token
                return JwtTokenUtil.verifyToken(token);
            }
            if (StringUtils.isBlank(token)) {
                return false;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(200);
        res.setContentType("application/json");
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "102");
        map.put("message", "请先登录系统！");
        writer.write(JSON.toJSONString(map));
        writer.close();
        return false;
    }
}
